package com.xwaf.platform.system.provider.config;

import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import com.xwaf.platform.system.provider.task.TestTask;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * <p>
 * 利用Quartz定时任务，可以在初始化上实现，
 * <p>
 * 
 * @author 李聪 <br>
 * @email xwaf_love@yeah.net <br>
 * @since JDK 1.8<br>
 * @date 2019年12月27日 下午5:05:45 <br>
 * @see 无<br>
 *      Copyright (c) 2019, xwaf_love@yeah.net All Rights Reserved.<br>
 */
@Slf4j
@Component
public class TaskApplicationListener implements ApplicationListener<ContextRefreshedEvent> {

	@Autowired
	SchedulerConfig schedulerConfig;

	public static AtomicInteger count = new AtomicInteger(0);
	private static String TRIGGER_GROUP_NAME = "TRIGGER_GROUP_NAME";
	private static String JOB_GROUP_NAME = "JOB_GROUP_NAME";

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		// 防止重复执行
		if (event.getApplicationContext().getParent() == null && count.incrementAndGet() <= 1) {
			initMyJob();
		}
	}

	public void initMyJob() {
		// 调度器
		Scheduler scheduler = null;
		try {
			// 创建scheduler
			scheduler = schedulerConfig.scheduler();
			// 定义一个TriggerKey
			TriggerKey triggerKey = TriggerKey.triggerKey("TestTaskBeanTest", TRIGGER_GROUP_NAME);
			CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
			if (null == trigger) {
				Class clazz = TestTask.class;
				// 定义一个JobDetail,其中的定义Job类，是真正的执行逻辑所在
				JobDetail jobDetail = JobBuilder.newJob(clazz).withIdentity("TestTask", JOB_GROUP_NAME).build();
				// CronScheduleBuilder scheduleBuilder =
				// CronScheduleBuilder.cronSchedule("0 */5 * * * ?");// 5分鐘
				CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule("1 * * * * ?");//
				// 定义一个Trigger
				trigger = TriggerBuilder.newTrigger().withIdentity("TestTaskBeanTest", TRIGGER_GROUP_NAME)
						.withSchedule(scheduleBuilder).build();
				scheduler.scheduleJob(jobDetail, trigger);
				log.info("Quartz 创建了job:...:{}", jobDetail.getKey());
			} else {
				log.info("job已存在:{}", trigger.getKey());
			}
			scheduler.start();
		} catch (Exception e) {
			log.info(ExceptionUtils.getFullStackTrace(e));
		}
	}
}
